new Vue({
    el: '#app',
    data: {
        loadingAddNote: false,
        // 用户信息
        userInfo: userInfo != null ? userInfo : {
            id: null,
            nickname: "未登录"
        },
        // 是否显示添加笔记的输入框
        showAddNoteCard: false,
        // 判断题答案，目前只在编辑时起作用
        editJudge: '',
        // 编辑题目对话框
        editDialogFormVisible: false,
        // 显示题目详情
        drawerDetails: false,
        loading: false,
        choiceOfAlpha: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'],
        // 多选框选中的题目
        selectedQuestion: [],
        // 选择的题型
        checkboxQuestions: [],
        // 题型
        questionKinds: ['选择题', '填空题', '判断题', '解答题'],
        // 表格里面的数据
        tableQuestions: [],
        // 分类categoryNames的index
        checkboxCategories: [],
        // 分类名
        categoryNames: [],
        // 分类详情
        categories: [],
        // 输入框输入题目内容
        inputQuestion: '',
        // 当前题目详情
        currentQuestion: {},
        // 当前编辑的题目详情
        currentEditQuestion: {
            // 题目类型
            kindInt: 0,
            // 题目类型
            kind: '',
            // 题目内容
            question: '',
            // id
            id: 0,
            // 选型内容
            choice: [''],
            // 答案
            answer: [''],
            // 状态
            status: 0,
            // 创建者id
            creator: 0,
            // 是否公开
            open: '',
            // 所属分类信息
            categories: [{
                id: null,
                name: '',
                // 是否公开
                open: null,
                status: null,
                creator: null
            }],
            // 所属分类名
            category: ''
        },
        // 当前题目的笔记
        currentNotes: [{}],
        // 新增笔记
        note: {
            content: '',
            open: false
        },
        openStatus: ['不公开', '公开'],
        // 正在修改笔记
        updatingNote: false,
        updateNote: {},
        loadingEditNote: false,
        curPrefixUrl: prefixUrl + gatewayPrefix.question,
        scrollContainer: null,
        debouncedHandleScroll: null,
        // 当前最后一道题的id，用于无限滚动
        lastQuestionId: null
    },
    methods: {
        // 筛选
        query() {
            // showAlert(this, "this.checkboxQuestions:" + this.checkboxQuestions +
            //     "\nthis.checkboxCategories:" + this.checkboxCategories)

            this.getMyQuestionByCondition();

        },
        // 添加数据到表格中
        addQuestionToTable(data) {
            for (let i = 0; i < data.length; i++) {
                if (i === data.length - 1) {
                    this.lastQuestionId = data[i].id;
                    console.log("this.lastQuestionId=" + this.lastQuestionId);
                }
                const categories = data[i].categories;
                console.log("categories=" + JSON.stringify(categories));
                // 获取分类名
                let categoryNamesOfAQuestion = '';
                if (categories != null && categories.length !== 0) {
                    categoryNamesOfAQuestion = categories[0].name;
                    for (let j = 1; j < categories.length; j++) {
                        const categoryNameOfAQuestion = categories[j].name;
                        categoryNamesOfAQuestion += ('、' + categoryNameOfAQuestion);
                    }
                }
                // 答案
                let answer = [data[i].answer.trim()];
                // 选项
                let choices;
                // 选择题
                if (data[i].kind === questionKind.choice) {
                    choices = data[i].choice.trim().split(split.default);
                    let tempAns = '';
                    for (let i = 0; i < answer[0].length; i++) {
                        tempAns += optoins[parseInt(answer[0].at(i))];
                    }
                    answer = [tempAns];
                }
                // 判断题
                else if (data[i].kind === questionKind.judge) {
                    if (answer[0] === '0') {
                        answer = [judge.yes];
                    } else {
                        answer = [judge.no];
                    }
                }
                // 填空题
                else if (data[i].kind === questionKind.blank) {
                    answer = data[i].answer.trim().split(split.default);
                }
                // 是否公开
                let open;
                if (data[i].open === openStatus.open) {
                    open = openStatus.yes;
                } else {
                    open = openStatus.no;
                }
                this.tableQuestions.push({
                    // 题目类型
                    kindInt: data[i].kind,
                    // 题目类型
                    kind: this.questionKinds[data[i].kind],
                    // 题目内容
                    question: data[i].question,
                    // id
                    id: data[i].id,
                    // 选型内容
                    choice: choices,
                    // 答案
                    answer: answer,
                    // 状态
                    status: data[i].status,
                    // 创建者id
                    creator: data[i].creator,
                    // 是否公开
                    open: open,
                    // 所属分类信息
                    categories: data[i].categories,
                    // 所属分类名
                    category: categoryNamesOfAQuestion
                });
            }
        },
        // 条件查询我的题目（题目内容、分类）
        getMyQuestionByCondition() {
            // 清空列表
            this.tableQuestions = [];
            this.loading = true;
            const url = this.curPrefixUrl + "/user/questions/condition/my";
            let categoryIds = [];
            for (let i = 0; i < this.checkboxCategories.length; i++) {
                let idx = this.checkboxCategories[i];
                // 如果当前分类已被删除，但是之前筛选题目的时候选中过
                if (idx >= this.categories.length) {
                    this.checkboxCategories.splice(i, 1);
                    continue;
                }
                categoryIds.push(this.categories[idx].id)
            }

            const questionQueryDTO = {
                question: this.inputQuestion,
                categoryIds: categoryIds,
                kinds: this.checkboxQuestions
            }
            console.log("questionQueryDTO:" + JSON.stringify(questionQueryDTO));
            axios.post(url, questionQueryDTO).then((resp) => {
                const result = resp.data;

                // data：ChoiceQuestionVO
                const data = result.data;
                // 添加数据到表格中
                this.addQuestionToTable(data);
            }).finally(() => {
                this.loading = false;
            });
        },
        // 继续加载题目
        loadQuestion() {
            console.log("loadQuestion");
            this.loading = true;
            const url = this.curPrefixUrl + "/user/questions/condition/my";
            let categoryIds = [];
            for (let i = 0; i < this.checkboxCategories.length; i++) {
                let idx = this.checkboxCategories[i];
                // 如果当前分类已被删除，但是之前筛选题目的时候选中过
                if (idx >= this.categories.length) {
                    this.checkboxCategories.splice(i, 1);
                    continue;
                }
                categoryIds.push(this.categories[idx].id)
            }
            const questionQueryDTO = {
                id: this.lastQuestionId,
                question: this.inputQuestion,
                categoryIds: categoryIds,
                kinds: this.checkboxQuestions
            }
            axios.post(url, questionQueryDTO).then((resp) => {
                const result = resp.data;
                // data：ChoiceQuestionVO
                const data = result.data;
                if (data.length === 0) {
                    showMsg(this, "没有更多题目了~");
                }
                // 添加数据到表格中s
                this.addQuestionToTable(data);
            }).finally(() => {
                this.loading = false;
            });
        },
        // 查看详情
        seeDetail(row) {
            // showAlert(this, row);
            // { "kindInt": 0, "kind": "选择题", "question": "", "id": 1, "choice": [], "answer": [ "B" ], "status": 1,
            // "creator": 1, "open": "是",
            // "categories": [ { "id": 1, "name": "数据结构", "status": 1, "open": 0,"creator": 1 }],
            // "category": "数据结构、数学" }
            this.currentQuestion = row;
            this.drawerDetails = true;

            // 获取笔记
            this.getNotesByQuestionId(this.currentQuestion.id);
        },
        // 获取题目对应的笔记
        getNotesByQuestionId(questionId) {
            const url = prefixUrl + "/note/user/notes/" + questionId;
            axios.get(url).then((resp) => {
                const result = resp.data;

                this.currentNotes = result.data;
                console.log("currentNotes=" + JSON.stringify(this.currentNotes));
            }).catch(() => {
            }).finally(() => {
            });
        },
        // 展示添加笔记卡片
        showAddNote() {
            this.showAddNoteCard = !this.showAddNoteCard;
        },
        // 添加笔记
        addNote() {
            let noteAddDTO = {
                questionId: this.currentQuestion.id,
                content: this.note.content,
                open: openStatus.notOpen
            };
            if (this.note.open) {
                noteAddDTO.open = openStatus.open;
            }
            // showAlert(this, noteAddDTO);
            const url = prefixUrl + "/note/user/notes";
            // 加载
            this.loadingAddNote = true;
            axios.post(url, noteAddDTO).then((resp) => {
                const result = resp.data;

                if (result.code === resultConstant.success) {
                    // 清空
                    this.note = {};
                    // 提示
                    showSuccessMsg(this, "笔记添加成功");
                    // 查询笔记
                    this.getNotesByQuestionId(this.currentQuestion.id);
                } else {
                    showErrorMsg(this, result.msg);
                }
            }).catch(() => {
            }).finally(() => {
                this.loadingAddNote = false;
            });
        },
        // 关闭题目详情
        closeDrawerDetails() {
            this.drawerDetails = false;
            this.currentQuestion = {};
            this.showAddNoteCard = false;
            this.note = {};
        },
        // 点击了删除
        deleteQuestion(row) {
            const _this = this;
            showConfirmAlert(this, msgConstant.deleteConfirm,
                function () {
                    // console.log("ok:" + JSON.stringify(row));
                    // showAlert(_this, row);
                    _this.deleteQuestionById(row.id);
                },
                function () {
                    // console.log("cancel:" + JSON.stringify(row));
                    showMsg(_this, msgConstant.cancelDelete);
                })
        },
        // 删除问题的具体操作
        deleteQuestionById(id) {
            console.log("deleteQuestionById:" + id)
            this.loading = true;
            const url = this.curPrefixUrl + "/user/questions/delete/" + id;
            axios.delete(url).then((resp) => {
                const result = resp.data;

                if (result.code === resultConstant.success) {
                    // 提示
                    showSuccessMsg(this, msgConstant.deleteSuccess);
                    // 查询题目
                    this.getMyQuestionByCondition();
                } else {
                    showErrorMsg(this, result.msg);
                }
            }).finally(() => {
                this.loading = false;
            });
        },
        // 编辑题目
        editQuestion(row) {
            // console.log("row=" + JSON.stringify(row));
            this.currentEditQuestion = copyByJSON(row);
            // 判断题答案
            if (this.currentEditQuestion.kindInt === questionKind.judge) {
                let judgeAns = '';
                if (this.currentEditQuestion.answer[0].trim() === judge.yes) {
                    judgeAns += judge.true;
                } else {
                    judgeAns += judge.false;
                }
                this.editJudge = judgeAns;
                console.log("judgeAns=" + judgeAns);
            }
            this.editDialogFormVisible = true;
        },
        // 取消编辑
        cancelEdit() {
            this.editDialogFormVisible = false;
            this.currentEditQuestion = {};
        },
        // 编辑完成，点击确定
        editFinish() {
            const questionEditDTO = {
                id: this.currentEditQuestion.id,
                question: this.currentEditQuestion.question,
                // kind: this.currentEditQuestion.kindInt,
                choice: '',
                answer: ''
                // status: this.currentEditQuestion.status,
                // open: this.currentEditQuestion.open
                // categories: this.currentEditQuestion.categories
            }
            // 选择题
            if (this.currentEditQuestion.kindInt === questionKind.choice) {
                // 将答案转为数字字符串
                const ans = this.currentEditQuestion.answer[0];
                let answerNum = '';
                for (let i = 0; i < ans.length; i++) {
                    let num = ans.at(i).charCodeAt(0) - 'A'.charCodeAt(0);
                    console.log("num=" + num);
                    answerNum += String(num);
                }
                console.log("answerNum=" + answerNum);
                questionEditDTO.answer = answerNum;
                // 将选项转为字符串
                let choice = '';
                choice = this.currentEditQuestion.choice.join(split.default);
                questionEditDTO.choice = choice;
            }
            // 填空题
            else if (this.currentEditQuestion.kindInt === questionKind.blank) {
                // 将多个填空转为字符串
                let answer = '';
                answer = this.currentEditQuestion.answer.join(split.default);
                questionEditDTO.answer = answer;
            }
            // 判断题
            else if (this.currentEditQuestion.kindInt === questionKind.judge) {
                // 将答案转为数字
                questionEditDTO.answer = this.editJudge;
            }
            // 解答题
            else if (this.currentEditQuestion.kindInt === questionKind.solve) {
                questionEditDTO.answer = this.currentEditQuestion.answer[0];
            }

            console.log("questionEditDTO=" + JSON.stringify(questionEditDTO));

            const url = this.curPrefixUrl + "/user/questions/edit";
            axios.put(url, questionEditDTO).then((resp) => {
                const result = resp.data;

                if (result.code === resultConstant.success) {
                    showSuccessMsg(this, '题目修改成功');
                } else {
                    showErrorMsg(this, result.msg);
                }

            }).catch(() => {

            }).finally(() => {

            });

            // showAlert(this, this.currentEditQuestion);
            // showAlert(this, questionEditDTO);

            this.editDialogFormVisible = false;
        },
        handleSelectionChange(val) {
            this.selectedQuestion = val;
            console.log("this.selectedQuestion=" + JSON.stringify(this.selectedQuestion))
        },
        // 获取我的所有分类
        getMyCategories() {
            this.loading = true;
            const url = this.curPrefixUrl + "/user/categories";
            // console.log("url=" + url)

            axios.get(url).then((resp) => {
                const result = resp.data;

                this.categories = result.data;
                // 清空分类名称
                this.categoryNames = [];
                // 设置分类名称
                for (let i = 0; i < this.categories.length; i++) {
                    this.categoryNames.push(this.categories[i].name);
                }
            }).finally(() => {
                this.loading = false;
            });
        },
        deleteSelectedQuestions() {
            // showAlert(this, "this.selectedQuestion=" + JSON.stringify(this.selectedQuestion))
            let ids = [];
            for (let i = 0; i < this.selectedQuestion.length; i++) {
                ids.push(this.selectedQuestion[i].id);
            }
            // showAlert(this, "ids=" + ids);
            const deleteManyDTO = {
                ids: ids
            }
            const url = this.curPrefixUrl + "/user/questions/delete/many";
            this.loading = true;
            axios.post(url, deleteManyDTO).then((resp) => {
                const result = resp.data;
                if (result.code === resultConstant.success) {
                    showMsg(this, '删除成功');
                    // 获取题目
                    this.query()
                } else {
                    showMsg(result.msg);
                }
            }).catch((error) => {
                showAlert(this, error);
            }).finally(() => {
                this.loading = false;
            });
        },
        // 批量删除
        deleteSome() {
            showConfirmAlert(this, '确定删除当前选择的题目吗？',
                () => {
                    this.deleteSelectedQuestions()
                },
                () => {
                    showMsg(this, '已取消删除');
                });
        },
        cancelEditNote() {
            this.updatingNote = false;
        },
        finishEditNote() {
            const noteUpdateDTO = {
                id: this.updateNote.id,
                content: this.updateNote.content,
                open: this.updateNote.open,
            };
            const url = prefixUrl + "/note/user/notes";
            this.loadingEditNote = true;
            axios.put(url, noteUpdateDTO).then((resp) => {
                const result = resp.data;
                if (result.code === resultConstant.success) {
                    showMsg(this, '修改成功');
                    // 获取笔记
                    this.getNotesByQuestionId(this.currentQuestion.id);
                } else {
                    showMsg(result.msg);
                }
            }).catch((error) => {
                showMsg(error);
            }).finally(() => {
                this.updatingNote = false;
                this.loadingEditNote = false;
            });
        },
        // 点击了编辑笔记
        editNote(note) {
            // showAlert(this, note);
            this.updateNote = {
                id: note.id,
                content: note.content,
                open: note.open + ""
            };
            this.updatingNote = true;
        },
        scrollToBottom() {
            // 确保找到了滚动容器
            if (this.scrollContainer) {
                // 滚动到底部
                this.scrollContainer.scrollTop = this.scrollContainer.scrollHeight;
            }
        },
        scrollToTop() {
            // 确保找到了滚动容器
            if (this.scrollContainer) {
                // 滚动到底部
                this.scrollContainer.scrollTop = 0;
            }
        },
        // el-table是否滚动到了最底部
        isScrolledToBottom() {
            this.scrollContainer = this.$refs.questionTable.$el.querySelector('.el-table__body-wrapper');
            if (this.scrollContainer) {
                const {scrollTop, scrollHeight, clientHeight} = this.scrollContainer;
                return scrollTop + clientHeight >= scrollHeight - 1;
            }
            return false;
        },
        handleScroll() {
            // console.log("scrollTop=" + this.scrollContainer.scrollTop);
            // console.log("scrollHeight=" + this.scrollContainer.scrollHeight);
            // console.log("clientHeight=" + this.scrollContainer.clientHeight);
            if (this.isScrolledToBottom()) {
                // 滚动到底部时执行的操作
                console.log("isScrolledToBottom");
                this.loadQuestion();
            }
            // else {
            //     console.log("not isScrolledToBottom");
            // }
        },
        my_debounce(func, wait) {
            if (typeof func !== 'function') {
                throw new TypeError('need a function');
            }
            wait = +wait || 0;

            let timeId = null;

            return function () {
                // console.log('滚动了滚动了');  // 测试时可放开
                const self = this;
                const args = arguments;

                if (timeId) {
                    clearTimeout(timeId);   // 清除定时器，重新设定一个新的定时器
                }
                timeId = setTimeout(() => {
                    func.apply(self, args); // arguments 是传给函数的参数，这里是 event  对象
                }, wait);
            }
        }
    },
    created() {
        // 查询我的分类
        this.getMyCategories();

        saveSessionStorage(this, storageKey.myQuestionData, () => {
            // 查询所有题目
            this.getMyQuestionByCondition();
        })
    },
    mounted() {
        // 获取el-table的scrollContainer
        this.scrollContainer = this.$refs.questionTable.$el.querySelector('.el-table__body-wrapper');
        // 监听滚动事件
        // 使用防抖技术限制 handleScroll 的执行频率
        this.debouncedHandleScroll = this.my_debounce(this.handleScroll, 100);
        this.$nextTick(() => {
            this.scrollContainer.addEventListener('scroll', this.debouncedHandleScroll);
        });
    },
    beforeDestroy() {
        this.scrollContainer.removeEventListener('scroll', this.debouncedHandleScroll);
    }
});